package org.chen.lock;

import org.chen.pool.JedisConnect;
import redis.clients.jedis.params.SetParams;

import java.util.Arrays;
import java.util.UUID;

public class LuaLockTest2 {
  public static final String SCRIPT="if redis.call('get',KEYS[1])==ARGV[1] " +
    "then \n"+
    "return redis.call('del',KEYS[1]) \n"+
    "else \n"+
    "return 0 \n"+
    "end";
  public static void main(String[] args) {
    final String[] sha1 = {""};
    JedisConnect connect = new JedisConnect();
    connect.execute(jedis -> {
      //加载脚本，返回sha1值
      sha1[0] = jedis.scriptLoad(SCRIPT);
      System.out.println(sha1[0]);
    });

    connect.execute(jedis -> {
      //获取随机字符串,锁的value值
      String value = UUID.randomUUID().toString();

      //获取锁
      String set = jedis.set("a1", value, new SetParams().nx().ex(10));

      //判断是否拿到锁
      if (set!=null&& "OK".equals(set)){//拿到锁了

        //具体业务操作
        jedis.set("hi","hello world!");
        System.out.println(jedis.get("hi"));

        //操作完成，释放锁 evalsha命令：使用内置的 Lua 解释器，可以对 Lua 脚本进行求值
        jedis.evalsha(sha1[0],
          Arrays.asList("a1"),Arrays.asList(value));
      }else {
        //没拿到锁
        System.out.println("没拿到锁");
      }
    });

  }
}
